package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ArticleMapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.service.ArticleService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;


    @Override
    public void add(Article article) {


        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());


       Map<String,Object> map =ThreadLocalUtil.get();

       Integer createId=(Integer) map.get("id");


       article.setCreateUser(createId);


       articleMapper.add(article);




    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {

        PageBean<Article> pb=new PageBean<>();


        //借助分页插件分页
        PageHelper.startPage(pageNum,pageSize);

        //借助ThreadLocal找到登录用户的id并给CreateUser赋值
       Map<String,Object> map =ThreadLocalUtil.get();

       Integer CreateUser=(Integer) map.get("id");


      List<Article> as =articleMapper.list(CreateUser,categoryId,state);

      //利用强转，调用Page里的值得到当前记录条数和页数

        Page<Article> p=(Page<Article>) as;

        //将数据填充到PageBean<Article>中并返回
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());


        return pb;


    }

    @Override
    public Article getById(Integer id) {
        return articleMapper.getById(id);
    }

    @Override
    public void update(Article article) {

        article.setUpdateTime(LocalDateTime.now());

        articleMapper.update(article);

    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
